package com.M10.BE.inventory;

import android.app.Activity;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.M10.BE.BEutils;
import com.M10.BE.CrashHandler;
import com.M10.BE.R;
import com.M10.BE.adapter.InveAdapter;
import com.fn.useries.model.Inve;
import com.fn.useries.model.Message;
import com.fn.useries.model.ResponseHandler;
import com.fn.useries.operation.U8Series;
import com.fn.useries.reader.model.InventoryBuffer;
import com.fn.useries.reader.server.ReaderHelper;
import com.fn.useries.utils.MusicPlayer;
import com.fn.useries.utils.StringTool;
import com.fn.useries.utils.Tools;
import com.hsm.barcode.DecoderException;
import com.hsm.barcode.ExposureValues;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import lib.kingja.switchbutton.SwitchMultiButton;

/**
 * @author LuoDaHai
 * @decs 资产盘点
 * @time 2018/3/8   15:19
 */
public class InveActivity extends Activity implements BEutils.RJ {

    @BindView(R.id.tv_inve_back)
    TextView tvInveBack;
    @BindView(R.id.rv_inventory)
    RecyclerView rvIinventory;
    //    @BindView(R.id.ttttt)
//    TextView ttttt;
//    @BindView(R.id.test)
//    TextView test;
//    @BindView(R.id.tv_inve_sq)
//    TextView tvInveSq;
//    @BindView(R.id.tv_inve_gy)
//    TextView tvInveGy;
    @BindView(R.id.smb_inve)
    SwitchMultiButton mSwitchMultiButton;
    @BindView(R.id.ll_inve_pro)
    LinearLayout llInvePro;
    @BindView(R.id.ll_inve_content)
    LinearLayout llInveContent;
    private InveAdapter adapter;
    public static InveActivity instance = null;
    private String TAG = "InveActivity";
    private static int g_ScanKey = BEutils.g_ScanKey;
    private static final int SCAN_KEY = BEutils.SCAN_KEY;//-1;		// Scan key default
    private U8Series mUSeries;
    private String model = "U8";
    private static InventoryBuffer m_curInventoryBuffer = null;
    ArrayList<Inve> inves;
    List<InventoryBuffer.InventoryTagMap> tagMapList;
    private ArrayList<String> users = new ArrayList<>();
    /**
     * 0===二维码  1===rfid
     */
    private int lable = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_inve);
        ButterKnife.bind(this);
        inves = (ArrayList<Inve>) getIntent().getSerializableExtra("inves");
        adapter = new InveAdapter(inves, this);
        rvIinventory.setLayoutManager(new LinearLayoutManager(this));
        rvIinventory.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        rvIinventory.setAdapter(adapter);
        instance = this;
        g_ScanKey = SCAN_KEY;

        BEutils.setBankListener(this);
        Log.d(TAG, "g_ScanKey=" + g_ScanKey);
        if (g_ScanKey == -1) // not initialized
        {
            Log.d(TAG, "Please define SCAN_KEY");
        }
//        init();
        CrashHandler crashHandler = CrashHandler.getInstance();
        crashHandler.init(getApplicationContext());

        mUSeries = U8Series.getInstance();
        U8Series.setContext(this);

        Message openSerialPortMeaasge = mUSeries.openSerialPort(model);
        if (openSerialPortMeaasge.getCode() != 0) {
            Log.e(TAG, "bt_u8 -----openSerialPortMeaasge: " + "/**\n" +
                    "\t * 若配置文件丟失,跳转到配置工具\n" +
                    "\t */");
            return;
        }
        try {
            m_curInventoryBuffer = ReaderHelper.getDefaultHelper().getCurInventoryBuffer();
        } catch (Exception e) {
            e.printStackTrace();
        }

        mSwitchMultiButton.setText("二维码扫描", "RFID感应").setOnSwitchListener(new SwitchMultiButton.OnSwitchListener() {
            @Override
            public void onSwitch(int position, String tabText) {
                lable = position;
            }
        });
    }

    @OnClick(R.id.tv_inve_back)
    public void onViewClicked() {
        BEutils.stopScaning();
        stopInventory();
        finish();
    }

    private void stopInventory() {

        try {
            mUSeries.stopInventory();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        Message powerOnMessage = mUSeries.modulePowerOn(model);
        if (powerOnMessage.getCode() != 0) {
            Log.e(TAG, "onResume: " + "/**\n" +
                    "\t * 若配置文件丟失,跳转到配置工具\n" +
                    "\t */");
        }


        BEutils.Decoder();
        new Thread(new BEutils.Task()).start();
        BEutils.bRunThread = true;

        int g_nExposureSettings[] =

                {
                        ExposureValues.ExposureSettings.DEC_ES_MAX_EXP, 130,
                };

        try {
            BEutils.m_Decoder.setExposureSettings(g_nExposureSettings);
            BEutils.m_Decoder.setExposureMode(ExposureValues.ExposureMode.HHP);
        } catch (DecoderException e) {
            BEutils.HandleDecoderException(e);
        }


        if (!BEutils.bAppRetainsPreferences) {
            BEutils.bAppRetainsPreferences = true;

            // Configure preference settings to defaults...
            Log.d(TAG, "Configure preference settings to defaults...");

            BEutils.SetSymbologyPreferences(true);
            BEutils.SetOcrPreferences(true);
            BEutils.SetDecodingPreferences(true);
            BEutils.SetScanningPreferences(true);
            BEutils.SetApplicationPreferences(true);
        }

        // Re-configure preferences based on user preferences...
        Log.d(TAG, "Configure preferences based on user settings...");
        try {
            //BEutils.SetSymbologySettings();
            BEutils.SetOcrSettings();
            BEutils.SetDecodingSettings();
            BEutils.SetScanningSettings();
            BEutils.SetApplicationSettings();
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        BEutils.Pause();
        stopInventory();
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
//        android.os.Process.killProcess(android.os.Process.myPid());
    }

    /**
     * Called when key is up 当键被松开时调用
     */
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {

        Log.d(TAG, "onKeyUp" + "keyCode=" + keyCode + "(g_ScanKey=" + g_ScanKey + ")");

//        if (keyCode == g_ScanKey) {
//
//            if (lable == 0) {
//                if (!BEutils.g_bContinuousScanEnabled) {
//                    BEutils.StopScanning();
//                    llInveContent.setVisibility(View.VISIBLE);
//                    llInveContent.setAlpha(1);
//                    llInvePro.setVisibility(View.GONE);
//                }
//            } else {
//                stopInventory();
//            }
//        } else {
//            return super.onKeyUp(keyCode, event);
//        }

        return false;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            BEutils.stopScaning();
            stopInventory();
            finish();
        } else if (keyCode == g_ScanKey) {
            llInvePro.setVisibility(View.VISIBLE);
            llInveContent.setAlpha((float) 0.7);
            llInveContent.setEnabled(false);
            if (lable == 0) {
                BEutils.Scanning();
            } else {
                readEPC();
            }

        } else {
            return super.onKeyDown(keyCode, event);
        }
        return super.onKeyDown(keyCode, event);
    }


    private void readEPC() {
        try {
//                U8Series.setContext(InveActivity.this);
            mUSeries = U8Series.getInstance();
            mUSeries.startInventory(new ResponseHandler() {
                @Override
                public void onFailure(String msg) {
                    super.onFailure(msg);
                    llInveContent.setVisibility(View.VISIBLE);
                    llInveContent.setAlpha(1);
                    llInvePro.setVisibility(View.GONE);
                    llInveContent.setEnabled(true);
                    stopInventory();
                    Toast.makeText(InveActivity.this, getResources().getText(R.string.Disk_failure) + msg, Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onSuccess(String msg, Object data, byte[] parameters) {
                    super.onSuccess(msg, data, parameters);
                    stopInventory();
//                    Toast.makeText(InveActivity.this, "感应完成", Toast.LENGTH_SHORT).show();
                    if (msg.equals(U8Series.REFRESHTEXT)) {
                        //todo

                    } else if (msg.equals(U8Series.REFRESHLIST)) {
                        tagMapList =
                                (List<InventoryBuffer.InventoryTagMap>) data;
                        Log.e(TAG, "onSuccess: " + tagMapList.get(0).strEPC);
                        llInveContent.setVisibility(View.VISIBLE);
                        llInveContent.setAlpha(1);
                        llInvePro.setVisibility(View.GONE);
                        llInveContent.setEnabled(true);
                        readUser();
//                                stopInventory();
                    } else {
                        Log.e("U8", "盘询成功,返回标识异常");
                    }
                }

            });
//                mHandler.postDelayed(mRefreshRunnable, 500);

//                btnStop.setEnabled(true);
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("Exception", "盘询成功,返回标识异常");
        }
    }

    private void readUser() {
        // 数据处理  bank 0x03==取user区的数据
        byte btMemBank = 0x03;
        byte btWordAdd = 0x00;
        byte btWordCnt = 0x00;
        byte[] btAryPassWord = null;


        try {
            btWordAdd = (byte) Integer.parseInt("0");
        } catch (Exception e) {
            MusicPlayer.getInstance().play(MusicPlayer.Type.MUSIC_ERROR);
            Toast.makeText(InveActivity.this, getResources().getString(R.string.param_start_addr_error), Toast.LENGTH_SHORT).show();
            return;
        }
        try {

            btAryPassWord = Tools.stringToByteArray("00 00 00 00".toUpperCase(Locale.ENGLISH));
            if (btAryPassWord.length != 4) {
                throw new Exception("password length not right");
            }
        } catch (Exception e) {
            MusicPlayer.getInstance().play(MusicPlayer.Type.MUSIC_ERROR);
            Toast.makeText(InveActivity.this, getResources().getString(R.string.param_password_error), Toast.LENGTH_SHORT).show();
            return;
        }
        try {
            btWordCnt = (byte) Integer.parseInt("8");
        } catch (Exception e) {
            MusicPlayer.getInstance().play(MusicPlayer.Type.MUSIC_ERROR);
            Toast.makeText(InveActivity.this, getResources().getString(R.string.param_data_len_error), Toast.LENGTH_SHORT).show();
            return;
        }

        if ((btWordCnt & 0xFF) <= 0) {
            MusicPlayer.getInstance().play(MusicPlayer.Type.MUSIC_ERROR);
            Toast.makeText(InveActivity.this, getResources().getString(R.string.param_data_len_error), Toast.LENGTH_SHORT).show();
            return;
        }
        if (tagMapList != null) {
            users.clear();
            for (int i = 0; i < tagMapList.size(); i++) {
                Message msg = null;

                try {
//                    msg = mUSeries.readTagMemory("cancel".getBytes(), btMemBank, btWordCnt, btWordAdd, btAryPassWord);
                    if (tagMapList.get(i).strEPC.toString().equalsIgnoreCase("cancel")) {
                        msg = mUSeries.readTagMemory(tagMapList.get(i).strEPC.toString().getBytes(), btMemBank, btWordCnt, btWordAdd, btAryPassWord);
                    } else {
                        String[] result = StringTool.stringToStringArray(tagMapList.get(i).strEPC.toString(), 2);
                        byte[] epcSelected = StringTool.stringArrayToByteArray(result, result.length);
                        msg = mUSeries.readTagMemory(epcSelected, btMemBank, btWordCnt, btWordAdd, btAryPassWord);

                    }
                    if (msg.getCode() == 0) {
                        users.add(msg.getResult());
                        Log.e(TAG, "readUser: " + msg.getResult() + ">>>" + tagMapList.get(i).strEPC.toString());
//                        test.setText(msg.getList());
                        MusicPlayer.getInstance().play(MusicPlayer.Type.OK);
                    } else {
//                        test.setText("");
                        MusicPlayer.getInstance().play(MusicPlayer.Type.MUSIC_ERROR);
                        Toast.makeText(InveActivity.this, msg.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(InveActivity.this, getResources().getText(R.string.Read_Tag_Failure), Toast.LENGTH_SHORT).show();
                    MusicPlayer.getInstance().play(MusicPlayer.Type.MUSIC_ERROR);
//                        Loger.disk_log("Read", "readTagMemoryException,info = " + e.toString(), "M10_U8");
                }
            }
            checkDatas(users);
        } else {
            Toast.makeText(InveActivity.this, "未感应到卡片信息", Toast.LENGTH_SHORT).show();
        }


    }

    /**
     * 批量比对
     *
     * @param strings
     */
    private void checkDatas(ArrayList<String> strings) {
        for (int i = 0; i < strings.size(); i++) {

            for (int j = 0; j < inves.size(); j++) {
                if (inves.get(j).getId().equals(strings.get(i).replace(" ", "").toLowerCase())) {
                    Log.e(TAG, "checkDatas2: " + strings.get(i).replace(" ", "").toLowerCase());
                    Log.e(TAG, "checkDatas1: " + inves.get(j).getId() + inves.get(j).getCode());
                    if (inves.get(j).getCheckNum().equals("0")) {
                        inves.get(j).setCheckNum("1");
                        Toast.makeText(this, "成功盘点资产+1", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(this, "当前资产已盘点", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }
        adapter.notifyDataSetChanged();
    }

    /**
     * 数据比对
     *
     * @param result
     */
    private void checkData(String result) {
        llInveContent.setVisibility(View.VISIBLE);
        llInveContent.setAlpha(1);
        llInvePro.setVisibility(View.GONE);
        llInveContent.setEnabled(true);
        for (int i = 0; i < inves.size(); i++) {
            if (inves.get(i).getId().equals(result)) {
                Log.e(TAG, "checkData: " + result);
                if (inves.get(i).getCheckNum().equals("0")) {
                    inves.get(i).setCheckNum("1");
                    adapter.notifyDataSetChanged();
                    Toast.makeText(this, "成功盘点资产+1", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "当前资产已盘点", Toast.LENGTH_SHORT).show();
                }

                return;
            }
        }
    }

    @Override
    public void fillBlank(String result) {
        llInveContent.setVisibility(View.VISIBLE);
        llInveContent.setAlpha(1);
        llInvePro.setVisibility(View.GONE);
        llInveContent.setEnabled(true);
        checkData(result);
//        Toast.makeText(this, result, Toast.LENGTH_SHORT).show();
    }
}
